package tn.orange.canreminder.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import tn.orange.canreminder.conf.Config;
import tn.orange.canreminder.model.JSONPlacesCategory;
import tn.orange.canreminder.model.Rate;
import tn.orange.canreminder.parse.GenericJsonParser;

public class SubmitRateServiceImp implements SubmitRate {

	GenericJsonParser parser = new GenericJsonParser();

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * tn.orange.canreminder.service.SubmitRate#submitRate(tn.orange.canreminder
	 * .model.Rate)
	 */
	@Override
	public void submitRate(Rate rate) throws Exception {

		GenericJsonParser parser = new GenericJsonParser();
		// TODO Auto-generated method stub
		HttpClient httpclient = new DefaultHttpClient();
		parser.setOutput(JSONPlacesCategory.class);
		parser.setUrl(Config.submitrate);

		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		nameValuePairs.add(new BasicNameValuePair("email", rate.getMail()));
		nameValuePairs.add(new BasicNameValuePair("rate", "" + rate.getRate()));
		nameValuePairs.add(new BasicNameValuePair("place_id", ""
				+ rate.getPlace_id()));

		HttpPost httppost = new HttpPost(Config.submitrate);

		httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
		HttpResponse httpResponse=httpclient.execute(httppost);

		StringBuilder response = inputStreamToString(httpResponse.getEntity()
				.getContent());

	}

	private StringBuilder inputStreamToString(InputStream is)
			throws IOException {
		String line = "";
		StringBuilder total = new StringBuilder();

		// Wrap a BufferedReader around the InputStream
		BufferedReader rd = new BufferedReader(new InputStreamReader(is));

		// Read response until the end
		while ((line = rd.readLine()) != null) {
			total.append(line);
		}

		// Return full string
		return total;
	}
}
